﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

using PriceLibrary.PriceService;

using VDataAdapter.Communication;
using VDataAdapter.QueueManagement;
using VDataAdapter.EventManagement;
using log4net;

namespace VDataAdapter.WorkerManagement
{
    class PutThroughWorkerException : Exception
    {
        public PutThroughWorkerException() : base() { }
        public PutThroughWorkerException(string msg) : base(msg) { }
        public PutThroughWorkerException(string msg, Exception inner) : base(msg, inner) { }
    }

    /// <summary>
    /// This class push PutThrough info to VData
    /// </summary>
    class PutThroughWorker : Worker
    {
        protected readonly ILog _log = LogManager.GetLogger(typeof(PutThroughWorker));

        private VDataCommunicator _sender;

        private IEventProviderQueue _eQueue;

        private EventQueueChecker _queueChecker;

        /// <summary>
        /// Let it starts only after transactions is sent
        /// He is hardworking too
        /// </summary>
        /// <param name="waitTransaction"></param>
        /// <param name="sender"></param>
        /// <param name="eQueue"></param>
        public PutThroughWorker(string parentName,ManualResetEvent waitTransaction, VDataCommunicator sender, IEventProviderQueue eQueue):
            base(waitTransaction, null, true)
        {
            _name = parentName+"-PutThroughWorker";
            _sender = sender;
            _eQueue = eQueue;
            _queueChecker = new EventQueueChecker(eQueue);
        }

        public bool StopCheckingQueue
        {
            get { return _queueChecker.StopCheckingQueue; }
            set { _queueChecker.StopCheckingQueue = value; }
        }

        override
        public void StopWork()
        {
            StopCheckingQueue = true;
        }

        protected override void DoWork(object data)
        {
            try
            {
                
                var e = (PtTopPricesChangedEvent)_queueChecker.CheckingQueue(EventType.PutThrough);

                _log.Info("PutThroughWorker working with list of : " + e.PtTopPricesList.Count);

                _sender.SendPutThrough(e.PtTopPricesList);
            }
            catch(Exception ex)
            {
                throw new PutThroughWorkerException("Unknown exception: ", ex);
            }
        }
    }
}
